
import numpy as np
import os
import PIL.Image


def get_patches(src_hw, patch_hw, overlap_hw):
    src_h, src_w = tuple(src_hw)
    patch_h, patch_w = tuple(patch_hw)
    overlap_h, overlap_w = tuple(overlap_hw)

    if overlap_h >= patch_h or overlap_w >= patch_w:
        raise ValueError('overlap must be smaller than patch')

    unique_h = patch_h - overlap_h
    unique_w = patch_w - overlap_w

    if src_h > patch_h:
        patch_num_h = (src_h - patch_h) // unique_h
        remainder_h = (src_h - patch_h) % unique_h
    else:
        patch_num_h = 0
        remainder_h = 0

    if src_w > patch_w:
        patch_num_w = (src_w - patch_w) // unique_w
        remainder_w = (src_w - patch_w) % unique_w
    else:
        patch_num_w = 0
        remainder_w = 0

    # print(patch_num_h, patch_num_w, remainder_h, remainder_w)

    def get_patch(h_offset, w_offset):
        h_end = min(src_h, h_offset + patch_h)
        w_end = min(src_w, w_offset + patch_w)
        return (h_offset, w_offset, h_end, w_end)

    def get_patches_h_fixed(h_offset):
        for j in range(patch_num_w + 1):
            w_offset = j * unique_w
            yield get_patch(h_offset, w_offset)

        if remainder_w != 0:
            w_offset = max(0, src_w - patch_w)
            yield get_patch(h_offset, w_offset)

    for i in range(patch_num_h + 1):
        h_offset = i * unique_h
        yield from get_patches_h_fixed(h_offset)

    if remainder_h != 0:
        h_offset = max(0, src_h - patch_h)
        yield from get_patches_h_fixed(h_offset)


def main(args):
    src_hw = list(map(int, args.src_hw.split(',')))
    dst_hw = list(map(int, args.dst_hw.split(',')))
    overlap_hw = tuple(int(x * args.overlap_factor) for x in dst_hw)
    for h_offset, w_offset, h_end, w_end in get_patches(src_hw, dst_hw, overlap_hw):
        print(h_offset, w_offset, h_end, w_end)


if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('src_hw', type=str, default='640,640')
    parser.add_argument('dst_hw', type=str, default='640,640')
    parser.add_argument('overlap_factor', type=float, default=0.25)
    args = parser.parse_args()
    main(args)
